Machine Code Programming

adjust: mov eax, num1 ; put number into register

To run this code in C++:

#include <stdio.h>
#include <stdlib.h>

int main (void) {
	int num = 10; // you can declare variables outside the assembly block

	// assembly block:
	_asm {
		mov eax, num
		add eax, 12
		mov num, eax
	}
	return 0;
}

Intel x86 Registers

The Accumulator

Example code:

Note: The first operand is the destination, the second operand is the source

For move operations, a register must be involved. You cannot move data directly from memory to memory. Also, for move operations the source operand is not changed or erased.

Basic Maths

For a basic high level instruction like

int num = count1 + count2 - 10;

In assembly, the accumulator stores the result of each step (accumulating the answer)

mov eax, count1
add eax, count2
sub eax, 10
mov num, eax

Addition and subtraction work as expected, for multiplication, only one operand is used which is the value to multiply the accumulator by, for example, to calculate 10*12

mov eax, 10
mov ebx, 12
mul ebx

^ This would result in 120 being stored in EAX

Division

mov ebx, 9
mov edx, 0
mov eax, 120
div ebx

Operation will set status flags if the result is too big or division by zero is attempted

Status flags

Important flags:

Unconditional Jump

An unconditional jump will move the IP to the given address label

       mov eax, 10
begin: add eax, 10
       jmp begin

The above code is an infinite loop that keeps adding 10 to EAX
Eventually, EAX would get too big and overflow
Jumping is unrestricted, so should take care to avoid messy code with jumps all over the place

Conditional Jumps

A conditional jump happens if a certain condition is true
If the condition is false, the IP moves to the next instruction
Jump instructions:

eg.

num = num - 10;
if (num==0) {
	num = 100;
}

this code in assembly would look like:

		mov eax, num
		sub eax, 10
		jnz store
		mov eax, 100
store:  mov num, eax

Comparing Values

If-Else in Assembly

if (num>0){
	pos = pos+num;
} else {
	neg = neg+num;
}

would be

		mov eax, num
		cmp eax, 0
		jg postv
negtv:  add neg, eax
		jmp endif
postv:  add pos, eax
endif:  ..
		..

Loops

Labels & Memory Addresses

Arrays

Array Processing

Subroutines